<template>
  <div>
    <van-nav-bar title="附近的充电站" left-text="返回" left-arrow @click-left="onClickLeft" />
  </div>
  <div style="margin: 8px 8px 20px 8px">
    <!-- 地图容器 -->
    <div id="container"></div>
  </div>
  <!-- 添加导航按钮 -->
  <div v-if="selectedStation" class="navigate-button">
    <button @click="startNavigation">开始导航</button>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { showFailToast } from "vant";
import axios from "axios";

// 地图相关变量
let map = null;
const longitude = ref(115.465000); // 设置默认经纬度
const latitude = ref(38.873899);  // 设置默认纬度
const selectedStation = ref(null); // 存储选择的充电站

// 监听返回按钮的点击事件
const onClickLeft = () => history.back();

// 在组件挂载时加载地图
onMounted(() => {
  loadMap();
});
window._AMapSecurityConfig = {

  securityJsCode: "aa2d8dc0b29b06848ea09d647e35d403",
}
// 加载地图并展示
function loadMap() {
  const apiKey = "7bd909e9189bc5c4831b4b66b411b12b";  // 高德地图API的key
  AMapLoader.load({
    key: apiKey,
    version: "2.0", // API版本
    plugins: ['AMap.Driving'], // 加载驾车导航插件
  })
      .then((AMap) => {
        // 初始化地图
        map = new AMap.Map("container", {
          viewMode: "3D",
          zoom: 11,
          center: [longitude.value, latitude.value], // 设置地图中心为用户当前经纬度
        });

        // 标记用户当前位置
        const userMarker = new AMap.Marker({
          position: new AMap.LngLat(longitude.value, latitude.value),
          title: "当前位置",
        });
        userMarker.setMap(map);

        // 获取充电桩数据并显示
        fetchChargingStations();
      })
      .catch(() => {
        showFailToast("获取地图失败");
      });
}

// 获取充电桩数据
function fetchChargingStations() {
  axios
      .get("http://localhost:8875/map/list")  // 后端接口
      .then((res) => {
        const chargingStations = res.data.data;  // 从后端获取的数据
        console.log(chargingStations);  // 打印结果，确保数据已经更新

        // 在地图上显示充电桩
        displayChargingStations(chargingStations);
      })
      .catch((error) => {
        console.error("获取充电站数据失败:", error);
        showFailToast("获取充电站数据失败，请稍后再试");
      });
}

// 在地图上显示充电桩
function displayChargingStations(stations) {
  stations.forEach(station => {
    const marker = new AMap.Marker({
      position: new AMap.LngLat(station.longitude, station.latitude),
      title: station.name,
      content: `<div>${station.name}</div>`, // 标记内容
    });
    marker.setMap(map);

    // 添加点击事件，显示充电站详情并设置为目标
    marker.on("click", () => {
      selectedStation.value = station;
      showStationDetails(station);
    });
  });
}

// 显示充电站详情
function showStationDetails(station) {
  alert(`充电站名称: ${station.name}\n地址: ${station.address}`);
}
window._AMapSecurityConfig = {

  securityJsCode: "aa2d8dc0b29b06848ea09d647e35d403",
}
// 开始导航
function startNavigation() {
  if (selectedStation.value) {
    const apiKey = "7bd909e9189bc5c4831b4b66b411b12b";  // 使用统一的 API Key
    AMapLoader.load({
      key: apiKey,  // 高德地图API的key
      version: "2.0",
      plugins: ['AMap.Driving'],
    }).then((AMap) => {
      const driving = new AMap.Driving({
        map: map,
        panel: "container", // 显示导航信息面板
      });

      // 起点：用户当前位置
      const start = new AMap.LngLat(longitude.value, latitude.value);
      // 终点：选择的充电站
      const end = new AMap.LngLat(selectedStation.value.longitude, selectedStation.value.latitude);

      console.log('起点:', start);
      console.log('终点:', end);

      // 开始驾车路径规划
      driving.search(start, end, (status, result) => {
        console.log('导航状态:', status);
        if (status === 'complete') {
          console.log('导航完成', result);
        } else {
          console.log('导航失败', result);
          showFailToast('导航失败，请稍后重试');
        }
      });
    });
  }
}

// 在组件卸载时销毁地图
onUnmounted(() => {
  map?.destroy();
});
</script>

<style scoped>
#container {
  width: 100%;
  height: 500px;
}

/* 样式 - 导航按钮 */
.navigate-button {
  text-align: center;
  margin-top: 20px;
}

.navigate-button button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
}

.navigate-button button:hover {
  background-color: #45a049;
}
</style>
